# from wo.goeasy import test_go
from flask import Blueprint, jsonify, request

from models.entity.project import Project
import json
from datetime import datetime

import requests
import json

from utils.result import result

mod = Blueprint("core_project", __name__, url_prefix="/core/project", template_folder="templates",
                static_folder="static")


@mod.route('/get_all/', methods=['GET', 'POST'])
def task_index():
    """获取全部项目"""
    tmp = {}
    data = []
    project = Project.query.all()
    for item in project:
        data.append(item.to_dict())
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)


@mod.route('/add/', methods=['GET', 'POST'])
def add_project():
    """增加设备"""
    """
    {
    "name":"ddddd",
    }
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
            name = data['name']
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)

        if Project().get_project_by_name(name):
            return result(success=0, error_code=-1, error_msg="名称已存在")
        project = Project()
        try:
            project.from_dict(data)
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg=e)
        if project.save() is False:
            return result(success=0,error_code=-4,error_msg="保存错误")
        else:
            return result(success=1,error_code=None,error_msg=None)


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_project():
    """编辑项目"""
    """
        {
        "id":1,
        "name":"项目2",

    }

    """
    if request.method == 'POST':
        try:
            dict = json.loads(request.data.decode("utf-8"))
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        tmp = {}
        data = []
        if "name" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "名称不能为空"
            tmp['data'] = data
            return jsonify(tmp)
        name = dict['name']
        the_project = Project.query.filter_by(id=dict['id']).first()
        if the_project.name != name and Project().get_project_by_name(name):
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "名称已经存在"
            tmp['data'] = data
            return jsonify(tmp)
        the_project.name = name
        if the_project.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "unknown error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/del/', methods=['GET', 'POST'])
def del_project():
    """删除项目"""
    """
    {
    "id":1
    }
    """
    tmp = {}
    data = []
    dict = json.loads(request.data.decode("utf-8"))
    id = dict['id']
    project = Project.query.filter_by(id=id).first()
    if not project:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "当前记录不存在，请重新选择"
        tmp['data'] = data
        return jsonify(tmp)
    if project.delete():
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        tmp['success'] = 0
        tmp['error_code'] = -2
        tmp['error_msg'] = "未知错误"
        tmp['data'] = data
        return jsonify(tmp)

# #
# @mod.route("/get_first_page/", methods=["GET", "POST"])
# def get_first_page():
#     # return result(success=1, data=session["auth"]["modules"])
#     return result(success=1, data=Project.get_project_by_pid())
#
# # 获取他的子集
# @mod.route('/get_children_by_project_id/', methods=['GET', 'POST'])
# def get_children_by_project_id():
#     """
#     根据id获取特定模块的子模块的列表
#     """
#     # request: json
#     # {
#     #       "pid":pid
#     # }
#     if request.method == "POST":
#         data = json.loads(request.data.decode("utf-8"))
#         pid = data.get('pid')
#         ret_list = Project().get_tree(pid)
#         return result(success=1, data=ret_list)









